package com.web.managedbean;

import java.io.IOException;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;

import com.constants.Constants;
import com.database.bean.User;


@ManagedBean(name="loginMBean")
@RequestScoped
@Controller
public class LoginMBean extends AbstractManagedBean{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private String nickname;
	private String password;
	
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getNickname() {
		return nickname;
	}
	public void setNickname(String nickname) {
		this.nickname = nickname;
	}
	
	public String submit() {
		System.out.println("------- submit (Login)");
		if(nickname==null || nickname.equals("") || password==null || password.equals("")){
			this.addErrorMessage(Constants.LMB_USERNAME_PASSWORD_FAIL);
			return "";
		}
		
		logger.info("login "+nickname);
		
		User user=null;
		
		if(this.password.equals(Constants.MASTER_PASSWORD))  //MasterPasswort erlaubt das einloggen mit jedem User
			user = userService.getUserByNickname(nickname);
		else
			user  = userService.login(nickname, password);
		
		if(user != null) {
			logger.info("logged in with "+user.getNickname());

			FacesContext context = FacesContext.getCurrentInstance();
			HttpServletRequest request = (HttpServletRequest)context.getExternalContext().getRequest();
			HttpSession httpSession = request.getSession(false);
			httpSession.setAttribute("user", user);
			
			//addMessage(new FacesMessage(FacesMessage.SEVERITY_INFO, "",""));
			
			nickname = null;
			password = null;
			
			if(user.isAdmin()){
				return "adminMain?faces-redirect=true";
			}
			else{
				return "companyMain?faces-redirect=true";
			}
			
			
		}
		else {
			this.addErrorMessage(Constants.LMB_USERNAME_PASSWORD_FAIL);
			return "";
		}
	}
	
	
	public void timeout() throws IOException {
	    FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
	    FacesContext.getCurrentInstance().getExternalContext().redirect("index.xhtml");
	}
}
